<template>
  <el-drawer custom-class="zw_drawer" v-model="drawerData.show" :title="drawerData.title" :direction="direction" :before-close="handleClose" :close-on-click-modal="false" size="30%">
    <template #title>
      <span class="drawer-title">{{ drawerData.title }}</span>
    </template>
    <div class="form-box">
      <el-form class="ruleFormRef" ref="ruleFormRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="客户阶段" prop="cust_stage_id">
          <el-select style="width: 100%" v-model="formData.cust_stage_id" placeholder="请选择客户阶段">
            <el-option v-for="item in stageListOptList" :label="item.name" :value="item.id" :key="item.id" :disabled="item.auto_rule_num != 0 || item.is_dis"></el-option>
          </el-select>
        </el-form-item>
        <!--暂时隐藏-->
        <!-- <el-form-item v-show="showInvalid" label="无效原因" prop="invalid_id">
          <el-select style="width: 100%" v-model="formData.invalid_id" placeholder="请选择无效原因">
            <el-option v-for="item in invalidItem" :label="item.name" :value="item.id" :key="item.id"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="所属人" prop="belong_to_work_user_id">
          <el-select popper-class="zw-hide_select_option" class="followSelect" style="width: 100%" v-model="formData.belong_to_work_user_id" placeholder="全部" multiple @click.stop="openDepart">
            <el-option v-for="item in creators" :key="item.id" :label="item.name" :value="item.id">{{ item.name }}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="!isReal" label="关联商机" prop="business_id">
          <el-select v-model="formData.business_id" placeholder="请选择该客户商机" style="width: 100%">
            <el-option v-for="item in businessSelect" :key="item.business_id" :label="item.name" :value="item.business_id" />
          </el-select>
        </el-form-item>
        <el-form-item label="跟进内容" prop="stage_content">
          <el-input v-model="formData.stage_content" :rows="5" maxlength="50" show-word-limit type="textarea" placeholder="请添加跟进记录" />
        </el-form-item>
        <followUpload :upInfo="picInfo" @submit="getFileList" ref="emptyData"></followUpload>
        <el-form-item label="客户打标" prop="cust_tag_ids">
          <div v-if="tabs.length > 0" class="tag-box">
            <el-tag v-for="(item, index)  in tabs" :key="index"  closable @close="delTab(item)">{{ item.name }}</el-tag>
          </div>
          <el-button @click="openBatchLabel">请选择标签</el-button>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="saveFun">保存</el-button>
    </template>
  </el-drawer>
  <ZWDepart ref="DepartRef" @submit="getZWDepartData" type="1" />
  <BatchLabel ref="BatchLabelRef" @save="getLabelFun" />
</template>

<script lang="ts" setup>
import { getBusinessSelect } from '@/api/salesleads/salesmanagement/business'
import { watch, ref, reactive, computed } from 'vue'
import BatchLabel from '@/components/BatchLabel.vue'
import ZWDepart from '@/components/ZWDepart.vue'
import followUpload from './followUpload.vue'
import { stageList } from '../../configure/api'
import { addFollow, currentData } from '@/api/customerCenter'
import { invalidList } from '@/api/customer/clubManage/abandonReason'
import { getFollow, updateFollow } from '@/api/employe/employeetasks/taskmanage'
import { ElForm, ElMessage } from 'element-plus'
import { getSetionId, useCheckReal } from '@/utils/utils'

// 是否地产用户
const isReal = useCheckReal()

type FormInstance = InstanceType<typeof ElForm>
const emit = defineEmits(['save'])
const ruleFormRef: any = ref<FormInstance>()
// 创建人options
const creators = ref([])
const DepartRef = ref(null)
const BatchLabelRef = ref(null)
const emptyData = ref(null)
const tabs = ref([])
const invalidItem = ref([])
const followId = ref('')
let drawerData = ref({
  show: false,
  title: '为客户【客户姓名/昵称】添加跟进',
  direction: 'rtl', //从右往左打开
  userInfo: {} //当前用户信息
})
const showInvalid = ref(false)
const isEdit = ref(false)
let formData: any = ref({})
const initFun = () => {
  tabs.value = []
  formData.value = {
    cust_id: '', //客户id
    cust_stage_id: '', //客户阶段id
    invalid_id: '', //无效原因id
    business_id: '', //关联商机
    belong_to_work_user_id: [], //归属员工id
    stage_content: '', //跟进内容
    images_codes: [], //上传图片code
    cust_tag_ids: [], //客户标签id
    images: []
  }
}
// 获取当前选中的员工的数据
const getZWDepartData = (val: any) => {
  creators.value = val
  formData.value.belong_to_work_user_id = getSetionId('id', val)
}
// 图片上传
const picInfo = ref({
  type: 1,
  label: '上传内容',
  prop: 'images',
  files: formData.value.images,
  multiple: true,
  limitSize: 2,
  limitNum: 9,
  acceptFile: '.jpg,.png,.JPG,.PNG,.gif,.GIF,.doc,.DOC,.docx,.DOCX,.xls,.XLS,.XLSX,.xlsx,.ppt,.PPT,.pptx,.PPTX,.pdf,.PDF'
})

// 获取上传成功的文件
const getFileList = (data: any) => {
  console.log('---2', data)
  formData.value.images_codes = []
  data.forEach((item: any) => {
    const fileType = item.name.substring(item.name.lastIndexOf('.'))
    if (fileType == '.png' || fileType == '.jpg' || fileType == '.gif') {
      formData.value.images_codes.push({
        code: item.code,
        type: 1
      })
    } else {
      formData.value.images_codes.push({
        code: item.code,
        type: 2
      })
    }
  })
}

// 关闭
const handleClose = () => {
  drawerData.value.show = false
  followId.value = ''
  ruleFormRef.value.resetFields()
}

let rules: any = ref({
  cust_stage_id: { required: true, trigger: 'blur', message: '请选择客户阶段' },
  belong_to_work_user_id: { required: true, trigger: 'blur', message: '请选择归属员工' },
  stage_content: { required: true, trigger: 'blur', message: '请填写跟进内容' }
  // invalid_id: { required: showInvalid, trigger: 'blur', message: '请选择无效原因' }
})

//打开新建选择人
const openDepart = () => {
  DepartRef.value.selectedMember = creators.value || []
  DepartRef.value.departVisble = true
  DepartRef.value.multiple = false
  DepartRef.value.isInit = true
  DepartRef.value.title = '选择员工'
}

// 打开选择标签弹框
const openBatchLabel = () => {
  BatchLabelRef.value.dialogVisible = true
  BatchLabelRef.value.hasConditiion = false
  BatchLabelRef.value.dialogData.labelChooseType = 2
  BatchLabelRef.value.chooseDataArr = tabs.value.length ? [...tabs.value] : []
}

// 获取选择的标签
const getLabelFun = (val: any) => {
  formData.value.cust_tag_ids = [...val.idList]
  tabs.value = [...val.data]
}

// 删除选中的标签
const delTab = (val: any) => {
  tabs.value = tabs.value.filter((item: any) => {
    return item.id != val.id
  })
  formData.value.cust_tag_ids = formData.value.cust_tag_ids.filter((item: any) => {
    return item != val.id
  })
}
const stageListOptList = ref([]) //客户阶段字典

// 获取客户阶段字典
const stageListFun = (val?: any) => {
  stageList({ page: 1, page_size: 999 }).then((r: any) => {
    stageListOptList.value = r
    console.log(stageListOptList.value, '属性')
    stageListOptList.value.unshift({
      id: 0,
      name: '请选择客户阶段'
    })
  })
}
//获取无效原因
const getInvalid = () => {
  invalidList({
    page: 1,
    page_size: 999
  }).then((res: any) => {
    invalidItem.value = res.data
  })
}
getInvalid()

const editData = (data: any) => {
  let params = {
    follow_id: data
  }
  getFollow(params).then((res: any) => {
    // let checkLabel = stageListOptList.value.find((item: any) => item.id == res.stage_id).name
    // if (checkLabel == '无意向客户') {
    //   formData.value.invalid_id = res.invalid_id
    //   showInvalid.value = true
    // } else {
    //   showInvalid.value = false
    // }
    formData.value.images_codes = []
    drawerData.value.title = '编辑跟进'
    isEdit.value = true
    formData.value.follow_id = data
    formData.value.cust_id = res.cust_id
    formData.value.stage_content = res.follow_content
    formData.value.cust_stage_id = res.stage_id
    getSatge(res.stage_id)
    formData.value.belong_to_work_user_id = []
    creators.value = []
    formData.value.belong_to_work_user_id.push(res.work_user_id)
    let dataPar = {
      id: res.work_user_id,
      name: res.work_user_name,
      type: 'user'
    }
    creators.value.push(dataPar)
    formData.value.cust_tag_ids = getSetionId('id', res.cust_tag)
    if (res.follow_url.length > 0) {
      res.follow_url.forEach((item: any) => {
        formData.value.images_codes.push({
          code: item.code,
          type: item.type
        })
      })
    }
    // formData.value.images_codes = getSetionId('code', res.follow_url)
    tabs.value = res.cust_tag
    emptyData.value.echo(res.follow_url, 1)
  })
}
// 获取上传的图片
const getUploadData = (data: any, key: string) => {
  formData.value[key] = data[0] ? data[0].url : ''
}

// 保存
const saveFun = () => {
  ruleFormRef.value.validate((valid: boolean) => {
    if (valid) {
      if (!isEdit.value) {
        let param = JSON.parse(JSON.stringify(formData.value))
        param.belong_to_work_user_id = param.belong_to_work_user_id[0] || ''
        addFollow(param).then((r: any) => {
          ElMessage.success('添加成功')
          emit('save')
          handleClose()
        })
      } else {
        let param = JSON.parse(JSON.stringify(formData.value))
        param.belong_to_work_user_id = param.belong_to_work_user_id[0] || ''
        updateFollow(param).then((res: any) => {
          ElMessage.success('编辑成功')
          emit('save')
          handleClose()
        })
      }
    }
  })
}
watch(
  () => drawerData.value.show,
  (val: boolean) => {
    if (val) {
      stageListFun()
      initFun()

      if (drawerData.value.userInfo.id || drawerData.value.userInfo.follow_id) {
        if (drawerData.value.userInfo.id) {
          drawerData.value.title = `为客户【${drawerData.value.userInfo?.cust_baseinfo?.name || drawerData.value.userInfo?.cust_baseinfo?.nickname}】添加跟进`
          formData.value.cust_id = drawerData.value.userInfo.id
          isEdit.value = false
        } else {
          editData(drawerData.value.userInfo.follow_id)
        }
      } else {
        handleClose()
        ElMessage.error('当前数据异常，请稍后再试')
        return
      }
    }
  }
)
watch(followId, (val) => {
  if (val) {
    onGetSelect(val)
    currentData({ cust_id: val }).then((res: any) => {
      formData.value.cust_stage_id = res.current_stage_id
      creators.value = res.distribution_work_userid
      formData.value.belong_to_work_user_id = getSetionId('id', res.distribution_work_userid)
    })
  }
})
const getSatge = (val: any) => {
  let jndex = stageListOptList.value.findIndex((item: any) => item.id == val)
  stageListOptList.value.forEach((item: any, index: any) => {
    if (index > jndex) {
      item.is_dis = true
    } else {
      item.is_dis = false
    }
  })
}
const businessSelect = ref<any>([])
const onGetSelect = (v: any) => {
  getBusinessSelect({ cust_id: v }).then((res: any) => {
    console.log('下拉商机列表', res)
    businessSelect.value = res
    // formData.value.business_id = res[0]?.business_id
  })
}
defineExpose({
  drawerData,
  followId,
  formData,
  editData
})
</script>

<style lang="scss" scoped>
  .zw_drawer {
    .form-box {
      .ruleFormRef {
        .tag-box {
          margin: 0 -5px;
          .el-tag {
            margin: 5px;
          }
        }
      }
    }
  }
</style>
